<template>
    <div class="app-container">
        <div class="tech-border-out">
            <div class="tech-border">
                <el-card>
                    <div slot="header" class="clearfix">
                        <dv-decoration-7 style="width:150px;height:30px;;"> <p style="padding: 0 15px;">设备列表</p>  </dv-decoration-7>
                    </div>
                    <div class="filter-container">
                            <el-input v-model="listQuery.name" placeholder="请输入设备名称" clearable style="width: 200px;margin-right: 10px;margin-bottom:10px" class="filter-item" @keyup.enter.native="handleFilter" />
                            <el-input v-model="listQuery.code" placeholder="请输入设备编码" clearable style="width: 200px;margin-right: 10px;margin-bottom:10px" class="filter-item" @keyup.enter.native="handleFilter" />
                            <el-cascader
                                   clearable
                                    placeholder="请选择设备分类"
                                    v-model="listQuery.cate_id"
                                    :options="category_list" 
                                    style="width: 200px;margin-right: 10px;margin-bottom:10px"
                                />
                            <el-select v-model.trim="listQuery.status" placeholder="请选择状态" clearable style="width: 200px;margin-right: 10px;margin-bottom:10px" class="filter-item">
                                <el-option v-for="(status, key) in statusOptions" :key="key" :value="parseInt(key)" :label="status"></el-option>
                            </el-select>

                        <el-button v-waves  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                        {{ '搜索' }}
                        </el-button>
                    <el-button v-waves v-if="checkPermission(['equipment.category.create'])"  class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
                        {{ "添加" }}
                    </el-button>  
                    </div>
                    <el-table
                    :header-cell-style="{background:'#eef1f6',color:'#606266'}"
                    :data="list"
                    size="medium"
                    fit
                    highlight-current-row
                    class="table-container"
                    style="width: 100%"
                    row-key="id"
                    max-height="950"
                    :tree-props="{children: 'children'}"
                        >  
                        
                    <el-table-column  align="left" label="设备名称" >
                        <template slot-scope="scope">
                            <span>{{ scope.row.name }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center"  label="设备编码" >
                        <template slot-scope="scope">
                            <span>{{ scope.row.code }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column  align="center" label="设备分类">
                        <template slot-scope="scope">
                            <span v-if="scope.row.cate">{{ scope.row.cate.name }}</span>
                            <span v-else>无</span>
                        </template>
                    </el-table-column>

                    <el-table-column align="center"  label="电量/电压/信号/温度/烟雾" >
                        <template slot-scope="scope">
                            <span></span>
                        </template>
                    </el-table-column>

                    <el-table-column  align="center" label="所属项目">
                        <template slot-scope="scope">
                            <span v-if="scope.row.project">{{ scope.row.project.title }}</span>
                            <span v-else>无</span>
                        </template>
                    </el-table-column>

                    <el-table-column  align="center" label="设备地址">
                        <template slot-scope="scope">
                            <span>{{ scope.row.province }} - {{ scope.row.city }} - {{ scope.row.area }} - {{ scope.row.address }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column  align="center" label="项目负责人">
                        <template slot-scope="scope">
                            <span v-if="scope.row.admin">
                                <div>{{ scope.row.admin.nickname }}</div>
                                <div> {{ scope.row.admin.phone }}</div>
                            </span>
                            <span v-else>无</span>
                        </template>
                    </el-table-column>

                    <el-table-column  align="center" label="排序">
                        <template slot-scope="scope">
                            <span>{{ scope.row.sort }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态"  align="center"  header-align="center">
                        <template slot-scope="scope">
                            <span class="status-badge" :class="`status-${scope.row.status}`">
                                {{ scope.row.status_text }}
                            </span>
                        </template>
                    </el-table-column>

                    <el-table-column  align="center" label="绑定时间">
                        <template slot-scope="scope">
                            <span>{{ scope.row.bind_time }}</span>
                        </template>
                    </el-table-column>

                    <!-- 操作列改为下拉菜单 -->
                    <el-table-column align="center" width="120" :label="'操作'">
                        <template slot-scope="scope">
                            <el-dropdown trigger="click" @command="handleCommand">
                                <el-button type="primary" size="mini">
                                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                                </el-button>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item 
                                        v-permission="['projects.edit']" 
                                        :command="{action: 'edit', index: scope.$index, row: scope.row}"
                                        icon="el-icon-edit"
                                    >
                                        编辑
                                    </el-dropdown-item>
                                    <el-dropdown-item 
                                        :command="{action: 'detail', index: scope.$index, row: scope.row}"
                                        icon="el-icon-document"
                                    >
                                        详情
                                    </el-dropdown-item>
                                    <el-dropdown-item 
                                        v-permission="['projects.delete']" 
                                        :command="{action: 'delete', index: scope.$index, row: scope.row}"
                                        icon="el-icon-delete"
                                    >
                                        删除
                                    </el-dropdown-item>
                                    <el-dropdown-item 
                                        :command="{action: 'location', index: scope.$index, row: scope.row}"
                                        icon="el-icon-location"
                                    >
                                        设备位置
                                    </el-dropdown-item>
                                    <!-- 可以继续添加更多操作 -->
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                    </el-table>
                    <dv-decoration-10 :dur="1" style="height:5px;" />
                </el-card>
            </div>
        </div>
       
        <el-dialog  width="850px"  :visible.sync="edit.dialogVisible"  :show-close="false" @close="getList" >
            <dv-border-box-11  class="el-new-dialog" title="编辑设备">
                <edit  :category_list="category_list"  :projects_list="projects_list"  :item="edit" />
            </dv-border-box-11>
        </el-dialog>
        <el-dialog width="850px"   :visible.sync="create.dialogVisible" @close="getList"  :show-close="false">
            <dv-border-box-11  class="el-new-dialog" title="添加设备">
                <create :category_list="category_list" :projects_list="projects_list"   :item="create" />
            </dv-border-box-11>
        </el-dialog>

        <!-- 设备位置弹窗 -->
        <el-dialog 
            :visible.sync="locationDialogVisible" 
            width="800px"
            :show-close="false"
        >
            <dv-border-box-11 class="el-new-dialog" title="设备位置">
                <div class="map-container">
                    <div id="baiduMap" style="width:100%;height:400px;"></div>
                    <div class="location-info">
                        <p><strong>设备名称：</strong>{{ currentDevice.name }}</p>
                        <p><strong>设备编码：</strong>{{ currentDevice.code }}</p>
                        <p><strong>详细地址：</strong>{{ currentDevice.province }} {{ currentDevice.city }} {{ currentDevice.area }} {{ currentDevice.address }}</p>
                        <p><strong>经纬度：</strong>{{ currentDevice.longitude }}, {{ currentDevice.latitude }}</p>
                    </div>
                </div>
            </dv-border-box-11>
        </el-dialog>
    </div>
</template>
<script>
    import waves from '@/directive/waves' // waves directive
    import permission from '@/directive/permission/index.js' // 权限判断指令
    import checkPermission from '@/utils/permission' // 权限判断函数
    import { list, detail, del,edit,equipment_switch } from '@/api/equipments' // api接口
    import { parseTime } from '@/utils' // 时间格式化函数
    import { getToken } from '@/utils/auth' // 获取token
    import Pagination from '@/components/Pagination' // 分页组件
    import Create from './components/list/create' // 添加组件  
    import Edit from './components/list/edit'  // 编辑组件  

    export default{
        name: 'equipmentList',
        components: { Pagination,Create,Edit }, // 引入组件
        filters: {
            parseTime // 时间过滤器
        },
        directives: { waves, permission }, // 引入指令
        data() {
            return {
                headerObj: {
                    'Authorization': 'Bearer ' + getToken()
                },
                map:null,
                list: [], // 列表数据
                total: 0, // 总条数
                select_ids : [], // 选中的id集合
                category_list : [], // 分类列表
                projects_list : [], // 项目列表
                listQuery: { //列表查询参数
                    page: 1,
                    limit: 10,
                    status:"",
                    name:"",
                    code:"",
                    cate_id:""
                },
                statusOptions: {
                    0: '离线',
                    1: '在线', 
                    2: '异常',
                    3: '报警',
                    4: '故障'
                },
                create: { // 新增
                    dialogVisible: false
                },  
                edit: { // 编辑
                    dialogVisible: false,
                    id: ''
                },  
                locationDialogVisible: false, // 设备位置弹窗
                currentDevice: {}, // 当前设备信息
                map: null // 百度地图实例
            }
        },
        created() {
            this.getList()
            // 异步加载百度地图
            this.loadBaiduMap()
        },
        methods: {
            checkPermission, // 权限判断函数
            
            // 加载百度地图
            loadBaiduMap() {
                // 检查是否已加载百度地图API
                if (window.BMap) {
                    return
                }
                const AK = 'QBpcAolFYBeJMwQSYultN9qiWwXJsd2D' // 替换为你的百度地图AK
                const script = document.createElement('script')
                script.type = 'text/javascript'
                script.src = `https://api.map.baidu.com/api?v=3.0&ak=${AK}&callback=baiduMapInit`
                document.head.appendChild(script)
                
                // 全局回调函数
                window.baiduMapInit = () => {
                    console.log('百度地图加载完成')
                }
                this.map = new BMapGL.Map('baidu-map');
            },
            
            // 初始化地图
            initMap(lng, lat) {
                if (!window.BMap) {
                    console.error('百度地图未加载')
                    return
                }
                
                const map = new BMap.Map('baiduMap')
                const point = new BMap.Point(lng, lat)
                map.centerAndZoom(point, 15)
                map.enableScrollWheelZoom(true)
                 // 禁用默认的被动事件监听
                map.getContainer().addEventListener('touchstart', (e) => {
                    e.preventDefault()
                }, { passive: false })
                
                map.getContainer().addEventListener('touchmove', (e) => {
                    e.preventDefault()
                }, { passive: false })
                map.setMapStyleV2({     
                    styleId: '38d3f16d7ca3975341fbd8e029e632c9'
                });
                
                // 添加标记
                const marker = new BMap.Marker(point)
                map.addOverlay(marker)
                
                // 添加信息窗口
                const infoWindow = new BMap.InfoWindow(`
                    <div style="padding:10px;">
                        <h4>${this.currentDevice.name}</h4>
                        <p>${this.currentDevice.code}</p>
                    </div>
                `)
                marker.addEventListener('click', () => {
                    map.openInfoWindow(infoWindow, point)
                })
                
                this.map = map
            },
            
            // 下拉菜单命令处理
            handleCommand(command) {
                const { action, index, row } = command
                switch (action) {
                    case 'edit':
                        this.handleEdit(index, row)
                        break
                    case 'delete':
                        this.handleDelete(index, row)
                        break
                    case 'detail':
                        this.handleDetail(index, row)
                        break
                    case 'location':
                        this.showDeviceLocation(row)
                        break
                }
            },
            // 跳转到详情页面
            handleDetail(index, row) {
                // 方式1：使用路由跳转（推荐）
                this.$router.push({
                    path: `/equipment/detail`,
                    query: {
                        id: row.id
                    }
                })},
            
            // 显示设备位置
            showDeviceLocation(row) {
                this.currentDevice = row
                this.locationDialogVisible = true
                
                // 确保经纬度存在
                if (!row.longitude || !row.latitude) {
                    this.$message.warning('该设备暂无位置信息')
                    return
                }
                
                // 下次DOM更新后初始化地图
                this.$nextTick(() => {
                    this.initMap(parseFloat(row.longitude), parseFloat(row.latitude))
                })
            },
            
            handleFilter() { // 查询
                this.listQuery.page = 1
                this.getList()
            },
            getStatusType(status) {
                const typeMap = {
                    0: 'info',      // 离线 - 灰色
                    1: 'success',   // 在线 - 绿色
                    2: 'warning',   // 异常 - 黄色
                    3: 'danger',    // 报警 - 红色
                    4: 'danger'     // 故障 - 红色
                }
                return typeMap[status] || 'info'
            },
            switch_status(row){
                equipment_switch({id:row.id,'status':row.status}).then(res => {
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                }).catch(err => {
                    this.$message.error(err.message);
                })
            },
            getList() { // 获取列表
                list(this.listQuery).then(response => {
                        this.list = response.data.data
                        this.total = response.data.total
                        this.category_list = response.data.category_list
                        this.projects_list = response.data.projects
                    })
                },
            handleCreate() { // 新增对话框显示
                this.create.dialogVisible = true
            },  
            handleEdit(index, row) { // 编辑对话框显示
                this.edit.dialogVisible = true
                this.edit.id = row.id
            },  
            handleDelete(index, row) { // 删除
                const thiz = this
                this.$confirm('确认要删除吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    del(row.id).then(() => {
                    this.$message({
                        message: '删除成功',
                        type: 'success',
                        duration: 1500,
                        onClose() {
                            thiz.getList();
                        }
                    })
                    })
                }).catch(() => {

                })
            }   
        }
    }
</script>
<style scoped> 
    ::v-deep .el-icon-arrow-right{
        color: #fff!important;
    }
    .el-cascader{
        width: 350px!important;
    }
    .status-badge {
        display: inline-block;
        padding: 2px 20px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 600;
        border-radius: 4px;
        text-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
        position: relative;
        overflow: hidden;
    }

    .status-badge::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
        transition: left 0.5s;
    }

    .status-badge:hover::before {
        left: 100%;
    }

    /* 状态颜色样式保持不变 */
    .status-0 {
        background: linear-gradient(135deg, #909399, #606266);
        color: white;
        border: 1px solid #5a5e66;
    }

    .status-1 {
        background: linear-gradient(135deg, #67c23a, #529b2e);
        color: white;
        border: 1px solid #4a8c29;
    }

    .status-2 {
        background: linear-gradient(135deg, #e6a23c, #d48220);
        color: white;
        border: 1px solid #c7731d;
    }

    .status-3 {
        background: linear-gradient(135deg, #f56c6c, #d63031);
        color: white;
        border: 1px solid #c12c2c;
        animation: pulse 2s infinite;
    }

    .status-4 {
        background: linear-gradient(135deg, #f56c6c, #c00000);
        color: white;
        border: 1px solid #a00000;
        box-shadow: 0 0 10px rgba(245, 108, 108, 0.5);
    }

    @keyframes pulse {
        0% { box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.7); }
        70% { box-shadow: 0 0 0 6px rgba(245, 108, 108, 0); }
        100% { box-shadow: 0 0 0 0 rgba(245, 108, 108, 0); }
    }

    /* 地图容器样式 */
    .map-container {
        padding: 10px;
    }

    .location-info {
        margin-top: 15px;
        padding: 15px;
        background: #07192E;
        border-radius: 4px;
    }

    .location-info p {
        margin: 5px 0;
        font-size: 14px;
    }

    /* 下拉菜单样式优化 */
    ::v-deep .el-dropdown-menu {
        min-width: 120px;
    }

    ::v-deep .el-dropdown-menu__item {
        text-align: center;
    }
</style>